<?php

namespace app\admin\controller;

use app\Request as R;
use app\admin\Validate;
use app\admin\model\AdminRole as Model;
use app\admin\model\AdminUser as UserModel;
use app\admin\middleware\Login;
use app\admin\service\RoleManger;

class Role extends BaseController{


    function index(R $req)
    {
        $page = $req->param('page/d');
        $page = $page<1?1:$page;
        return view("/role/index",[
            'datalist'=>app(RoleManger::class)->all()
        ]);
    }


    function add(R $req)
    {
        if($req->isPost()){
            $data = $req->only(['title','rules','desc']);
            $this->getRoleMangerService()->insert($data);
            return success_json("添加成功");
        }
        return view("/role/add");
    }

    function edit(R $req)
    {
        /** @var Model */
        $role = app(RoleManger::class)->find($req->route('id/d'));
        if(!$role){
            return error("找不到该用户组");
        }
        if($req->isPost()){
            $data = $req->only(['title','rules','desc']);
            app(RoleManger::class)->update($role['id'],$data);
            return success_json("修改成功");
        }
        return view("/role/edit",['model'=>$role]);
    }

    function delete(R $req)
    {
        $id = $req->route('id');
        app(RoleManger::class)->delete($id);
        return success_json("删除成功");
    }

    protected function addVali()
    {
        return new class extends Validate{
            protected $rule = [
                'title'  =>  'require|max:32',
                'desc' =>  'max:255',
                'rules'=>'array|require|check_re',
            ];
            protected $message = [
                'title.require'=>"标题不能为空",
                'title.max'=>"标题最大为32个字符",
                'desc.max'=>'描述最大为255个字符',
                'rules.array'=>'规则最少添加一项'
            ];
            function check_re($values){
                foreach($values as $value){
                    if( false !== $index =strpos($value,"*") && substr($value,-2) !== '/*'){
                        return "*必须在最后一位并且必须以/*结尾";
                    }
                }
                return true;
            }
        };
    }

    protected function editVali()
    {
        return $this->addVali();   
    }


    /**
     * @return \app\admin\service\RoleManger
     */
    function getRoleMangerService()
    {
        return app(\app\admin\service\RoleManger::class);
    }
}